package main

import (
	"time"

	"xagent/internal/actors"
	"xagent/internal/knowledge"
	"xagent/internal/team"
	proto "xagent/proto/v1"

	"github.com/asynkron/protoactor-go/actor"
	"github.com/sirupsen/logrus"
)

func init() {
	// 配置全局日志
	logrus.SetFormatter(&logrus.TextFormatter{
		FullTimestamp:   true,
		TimestampFormat: "2006-01-02 15:04:05",
	})
	logrus.SetLevel(logrus.DebugLevel)
}

func main() {
	logrus.Info("Starting team collaboration example")

	// 创建 actor system
	system := actor.NewActorSystem()
	logrus.Info("Actor system created")

	// 创建知识库引擎
	rag := knowledge.NewRAGEngine(&knowledge.Config{
		EmbeddingModel: "text-embedding-ada-002",
		VectorStore:    "inmemory",
	})
	logrus.Info("Knowledge base engine created")

	// 创建团队
	xteam := team.NewTeam("project-team", system, rag)
	logrus.WithField("team_name", "project-team").Info("Team created")

	// 创建并雇佣各个角色
	roles := []struct {
		name        string
		role        string
		description string
	}{
		{"product-manager-1", "product_manager", "Product vision and requirements specialist"},
		{"architect-1", "architect", "System architecture and design specialist"},
		{"engineer-1", "engineer", "Software engineer responsible for implementation"},
		{"domain-expert-1", "domain_expert", "E-commerce domain expert"},
		{"devops-1", "devops_engineer", "Infrastructure and deployment specialist"},
		{"qa-1", "qa_engineer", "Quality assurance specialist"},
		{"researcher-1", "researcher", "Research and analysis specialist"},
		{"tester-1", "tester", "Software testing specialist"},
	}

	for _, r := range roles {
		agent := actors.NewAIAgent(r.name, r.description)
		agent.SetKnowledgeBase(rag)
		if err := xteam.Hire(agent); err != nil {
			logrus.WithError(err).WithField("role", r.role).Error("Failed to hire agent")
			return
		}
		logrus.WithFields(logrus.Fields{
			"name": r.name,
			"role": r.role,
		}).Info("Agent hired")
	}

	// 定义任务列表
	tasks := []struct {
		id          string
		name        string
		description string
		assignAfter time.Duration
	}{
		{
			"pm-task-1",
			"AnalyzeRequirement",
			"分析电商系统需求,创建用户故事和产品规格说明",
			0,
		},
		{
			"architect-task-1",
			"SystemDesign",
			"设计电商系统架构,包括技术选型、系统组件、数据模型等",
			2 * time.Second,
		},
		{
			"expert-task-1",
			"ValidateDesign",
			"验证系统设计是否符合电商领域最佳实践",
			4 * time.Second,
		},
		{
			"engineer-task-1",
			"ImplementCode",
			"实现电商系统核心功能",
			6 * time.Second,
		},
		{
			"tester-task-1",
			"RunTests",
			"执行系统测试,包括单元测试、集成测试和性能测试",
			8 * time.Second,
		},
		{
			"qa-task-1",
			"QualityCheck",
			"进行质量检查,确保代码质量和测试覆盖率",
			10 * time.Second,
		},
		{
			"devops-task-1",
			"Deployment",
			"部署系统到生产环境,配置监控和告警",
			12 * time.Second,
		},
	}

	// 按顺序分配任务
	for _, t := range tasks {
		time.Sleep(t.assignAfter)

		task := &proto.Task{
			Id:          t.id,
			Name:        t.name,
			Description: t.description,
			Status:      proto.TaskStatus_TASK_STATUS_PENDING,
			Metadata: map[string]string{
				"created_at": time.Now().Format(time.RFC3339),
			},
		}

		logrus.WithFields(logrus.Fields{
			"task_id":    task.Id,
			"task_name":  task.Name,
			"created_at": task.Metadata["created_at"],
		}).Info("Assigning new task")

		if err := xteam.AssignTask(task); err != nil {
			logrus.WithError(err).WithField("task_id", task.Id).Error("Failed to assign task")
			continue
		}

		// 等待一段时间让任务处理
		time.Sleep(2 * time.Second)

		// 获取并打印团队指标
		metrics := xteam.GetTeamMetrics()
		logrus.WithFields(logrus.Fields{
			"metrics": metrics,
		}).Info("Current team metrics")
	}

	// 最终团队指标
	metrics := xteam.GetTeamMetrics()
	logrus.WithFields(logrus.Fields{
		"final_metrics": metrics,
	}).Info("Final team metrics")

	// 清理资源
	logrus.Info("Shutting down actor system")
	system.Shutdown()
}
